smooth out vec4 light_color;

uniform vec2 chunk_pos;
uniform float wind;
uniform int underwater;

vec4 biome_grass = vec4(0.4, 0.8, 0.3, 1.0);

vec3 vVertex;
vec3 eyeVec;
vec3 N;

vec4 calculateLight(ge_struct_Light light, float spec){
	vec4 final_color = light.ambient;
	if(light.attenuation == -1.0){
		return vec4(0.0);
	}else{
		vec3 L = normalize(light.vector - vVertex);
		float lambertTerm = dot(N, L);
		if(lambertTerm > 0.0){
			final_color += light.diffuse * lambertTerm;
			if(spec > 0.0){
				vec3 E = normalize(eyeVec);
				vec3 R = reflect(-L, N);
				float specular = pow(max(dot(R, E), 0.0), 2.0);
				final_color += spec * vec4(specular);
			}
		}
	}

	final_color.a = 1.0;
	return final_color;
}

void main(){
	vec4 pos = ge_VertexPosition;
	pos.xy += chunk_pos;
	ge_Color = vec4(1.0);
	ge_TexCoord0 = ge_VertexTexcoord;

	N = ge_MatrixNormal * normalize(ge_VertexNormal);
	vVertex = vec3(ge_MatrixModelView * pos);
	eyeVec = -vVertex;

	light_color = calculateLight(ge_StaticLights[0], ge_VertexColor.g);
	light_color.rgb *= ge_VertexColor.r;

	if(ge_VertexColor.b == 1.0){
		ge_Color *= biome_grass;
	}

	float anim = wind * 2.0;
	int anim_mode = int(ge_TexCoord0.z / 10.0) % 10;
	int n_anims = int(ge_TexCoord0.z / 100.0);
	float tex_h = mod(ge_TexCoord0.z, 1.0);

	if(anim_mode == 1){
		anim = (anim + 0.5) / 1.5;
		vec2 anim_v = (vec2(cos(ge_Time + pos.x * 0.1), sin(ge_Time + pos.y * 0.1)) + 1.0) / 2.0;
		anim = anim * length(anim_v);

		vec3 p = vec3(sin(ge_Time * 0.1), cos(ge_Time * 0.1), 0.0);
		pos.x += 0.75 * anim * p.x;
		pos.y += 0.75 * anim * p.y;
	}else
	if(anim_mode == 2){
		vec2 anim_v = (vec2(cos(ge_Time + pos.x * 0.1), sin(ge_Time + pos.y * 0.1)) + 1.0) / 2.0;
		anim = anim * length(anim_v);

		vec3 p = vec3(sin(ge_Time * 0.1), cos(ge_Time * 0.1), 0.0);
		p.xy *= cos(pos.z * 20.0);
		pos.x += 0.4 * anim * p.x;
		pos.y += 0.4 * anim * p.y;
	}else
	if(anim_mode == 9){
		pos.z -= 0.25 * (1.0 + (wind + 1.0) * 0.5 * cos(ge_Time + pos.x * 0.5) * sin(ge_Time + pos.y * 0.5));
	}

	if(n_anims > 1){
		ge_TexCoord0.y += tex_h * mod(floor(ge_Time * 20.0), float(n_anims));
	}

	ge_Position = ge_MatrixProjection * ge_MatrixModelView * pos;
}